package com.xiaoshi;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.xiaoshi.system.entity.BaseEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * <p>
 * mysql 代码生成器演示例子
 * </p>
 *
 * @author jobob
 * @since 2018-09-12
 */
public class MysqlGenerator {

//    private static String url = "jdbc:mysql://127.0.0.1:3306/hyd?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai";
//    private static String driverName = "com.mysql.cj.jdbc.Driver";
//    private static String username = "root";
//    private static String password = "admin";

//    private static String url = "jdbc:mysql://192.168.3.11:3306/hyd_log?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai";
    private static String url = "jdbc:mysql://192.168.3.15:3306/on_manger_system?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai";
    private static String driverName = "com.mysql.jdbc.Driver";
    private static String username = "root";
//    private static String password = "123456";
    private static String password = "123456";


    private static String parentPkg = "com.xiaoshi";
    private static String author = "yuankai";

    /**
     * <p>
     * 读取控制台内容
     * </p>order
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * RUN THIS
     */
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setFileOverride(false);// 是否覆盖同名文件，默认是false
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(author);
        gc.setOpen(false);
        //gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(url);
        dsc.setDriverName(driverName);
        dsc.setUsername(username);
        dsc.setPassword(password);
        dsc.setTypeConvert(new CustomTypeConvert());
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent(parentPkg);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();

//        strategy.setSuperEntityClass(BaseEntity.class);
        strategy.setEntitySerialVersionUID(true);
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setInclude(scanner("表名"));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");

        strategy.setEntityColumnConstant(true);

        mpg.setStrategy(strategy);
        // 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }















    static class CustomTypeConvert implements ITypeConvert{

        @Override
        public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
            String t = fieldType.toLowerCase();
            if (t.contains("char")) {
                return DbColumnType.STRING;
            } else if (t.contains("bigint")) {
                return DbColumnType.LONG;
            } else if (t.contains("tinyint(1)")) {
                return DbColumnType.BOOLEAN;
            } else if (t.contains("int")) {
                return DbColumnType.INTEGER;
            } else if (t.contains("text")) {
                return DbColumnType.STRING;
            } else if (t.contains("bit")) {
                return DbColumnType.BOOLEAN;
            } else if (t.contains("decimal")) {
                return DbColumnType.BIG_DECIMAL;
            } else if (t.contains("clob")) {
                return DbColumnType.CLOB;
            } else if (t.contains("blob")) {
                return DbColumnType.BLOB;
            } else if (t.contains("binary")) {
                return DbColumnType.BYTE_ARRAY;
            } else if (t.contains("float")) {
                return DbColumnType.FLOAT;
            } else if (t.contains("double")) {
                return DbColumnType.DOUBLE;
            } else if (!t.contains("json") && !t.contains("enum")) {
                if (t.contains("date") || t.contains("time") || t.contains("year")) {
                    byte var5;
                    switch(globalConfig.getDateType()) {
                        case ONLY_DATE:
                            return DbColumnType.DATE;
                        case SQL_PACK:
                            var5 = -1;
                            switch(t.hashCode()) {
                                case 3076014:
                                    if (t.equals("date")) {
                                        var5 = 0;
                                    }
                                    break;
                                case 3560141:
                                    if (t.equals("time")) {
                                        var5 = 1;
                                    }
                                    break;
                                case 3704893:
                                    if (t.equals("year")) {
                                        var5 = 2;
                                    }
                            }

                            switch(var5) {
                                case 0:
                                    return DbColumnType.DATE_SQL;
                                case 1:
                                    return DbColumnType.TIME;
                                case 2:
                                    return DbColumnType.DATE_SQL;
                                default:
                                    return DbColumnType.TIMESTAMP;
                            }
                        case TIME_PACK:
                            var5 = -1;
                            switch(t.hashCode()) {
                                case 3076014:
                                    if (t.equals("date")) {
                                        var5 = 0;
                                    }
                                    break;
                                case 3560141:
                                    if (t.equals("time")) {
                                        var5 = 1;
                                    }
                                    break;
                                case 3704893:
                                    if (t.equals("year")) {
                                        var5 = 2;
                                    }
                            }

                            switch(var5) {
                                case 0:
                                    return DbColumnType.DATE;
                                case 1:
                                    return DbColumnType.DATE;
                                case 2:
                                    return DbColumnType.YEAR;
                                default:
                                    return DbColumnType.DATE;
                            }
                    }
                }

                return DbColumnType.STRING;
            } else {
                return DbColumnType.STRING;
            }
        }
    }
}
